# -*- coding:utf-8 -*-
import csv
import threading

import pymysql
import requests
import json

import time


import os

from click._compat import raw_input

'''
1、处理闲聊增加的语句接口响应
2、暂时重构


'''
class smallTalkTest():
    '''获取token'''

    def login_token(self):
        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15012345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url, data=login_data, headers=login_header)

        # 获取登录的响应报文
        print(r_login.text)
        # login_response = json.loads(r_login.text)
        # 保存登录的token信息
        # access_token = login_response['access_token']
        token = r_login.json()['access_token']
        print(token)
        '''请求接口获取token值'''
        return token


    # def smallTalk(self,threadNum):
    #     # 初始化
    #     food_flag_init = 0
    #     qa_error_init = 0
    #     food_fail_init = 0
    #
    #     # 开始时间
    #     start = time.time()
    #
    #     #判断文件是否存在，存在则删除
    #     os.remove('E:\\test\\HB\\small_answer.csv')
    #
    #
    #     #闲聊的msg
    #     with open('E:\\test\\HB\\small_talk_init_one.csv', 'r') as smf:
    #         reader = csv.reader(smf)
    #         next(reader)
    #         for row in reader:
    #             small_talk_msg = {"msg":row[0]}
    #             small_talk_headers = {"Authorization": "Bearer " + self.login_token()}
    #
    #             # 闲聊的url
    #             small_talk_url = 'https://api.icarbonx.com/chit/st'
    #             # 闲聊的接口请求
    #             r_sm = requests.post(url=small_talk_url,data= small_talk_msg,headers= small_talk_headers)
    #             # 打印闲聊的响应结果
    #             print(r_sm.text)
    #
    #             #转换响应结果为dict格式
    #             r_sm_response = json.loads(r_sm.text)
    #
    #             # 断言响应结果
    #             if r_sm_response:
    #                 print(r_sm_response[0])
    #                 r_sm_all = r_sm_response[0]
    #                 r_sm_answer = r_sm_all['answer']
    #
    #                 r_sm_question = r_sm_all['question']
    #
    #             else:
    #                 qa_error_init = qa_error_init + 1
    #                 print("qa问答失败%d" %qa_error_init)
    #
    #             data_row = ['question', 'answer']
    #             if '\n' in r_sm_answer:
    #                 r_sm_answer = r_sm_answer.replace("\n", ";")
    #
    #             # 去掉回答结果中的逗号
    #             # r_sm_answer = r_sm_answer.replace(",", "")
    #
    #             # 保存chit的answer到本地文件
    #             with open('E:\\test\\HB\\small_answer.csv', 'a', encoding='utf-8-sig') as f:
    #                 # csv_write = csv.writer(f)
    #                 data_row[0] = row[0]
    #                 data_row[1] = r_sm_answer
    #
    #                 # data_row = list(data_row)
    #                 # print(data_row)
    #                 f.write(','.join(data_row))
    #                 f.write("\n")
    #                 # f.write("\\n")
    #
    #                 f.close()
    #
    #         # 关闭csv
    #         smf.close()
    #         # 计算花费的时间
    #         print('cost time:{}'.format(time.time() - start))
    #         print("------qa闲聊模型结果统计" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "------")
    #         print("qa问答无反馈%d" % qa_error_init)


    # 重构读取csv文件
    def readCsv(self):
        with open('E:\\test\\HB\\small_talk_init_one.csv', 'r') as smf:
            f1 = smf.readlines()
            print(f1)
            print(type(f1))
        return f1
            # reader = csv.reader(smf)
            # next(reader)
            # for row in reader:
            #     print(row[0])
            # return row[0]

    # 请求闲聊接口
    def chatChit(self):

        small_talk_msg_temp =self.readCsv()
        print(small_talk_msg_temp)
        print(type(small_talk_msg_temp))
        for i in range(len(small_talk_msg_temp)):
            msg_temp = small_talk_msg_temp[i]
            print(msg_temp)
            print(type(msg_temp))
            # 去掉回复中的特殊符号
            if '\n' in msg_temp:
                msg_temp = msg_temp.replace("\n", ";")
            small_talk_msg = {'msg':msg_temp}
            print(small_talk_msg)

        # print(self.readCsv())
        # small_talk_msg = {'msg':self.readCsv()}
            small_talk_headers = {"Authorization": "Bearer " + self.login_token()}
            #闲聊的url
            small_talk_url = 'https://api.icarbonx.com/chit/st'
            #闲聊的接口请求
            r_sm = requests.post(url=small_talk_url,data=small_talk_msg,headers=small_talk_headers)
        #返回闲聊结果，转换为json格式
            r_sm_response = json.loads(r_sm.text)
            print(r_sm_response)
            print(type(r_sm_response))
        return r_sm_response

    # 断言响应结果
    def assert_sm(self):
        qa_error_init = 0
        if self.chatChit():
            print(self.chatChit())
            r_sm_all = self.chatChit()[0]
            r_sm_answer = r_sm_all['answer']

            r_sm_question = r_sm_all['question']

        else:
            qa_error_init = qa_error_init + 1
            print("qa问答失败%d:"%qa_error_init)
        # 去掉回复中的特殊符号
        if '\n' in r_sm_answer:
            r_sm_answer = r_sm_answer.replace("\n",";")

        #去掉回复中的逗号
        r_sm_answer = r_sm_answer.replace(",","")
        print(r_sm_answer)
        print(qa_error_init)
        print(type(r_sm_answer))
        print(type(qa_error_init))
        return r_sm_answer,qa_error_init

    # 保存接口响应结果到本地文件
    def saveCsv(self):
        # data_row = ['question','answer']
        data_row = ['answer']

        with open('E:\\test\\HB\\small_answer.csv', 'a', encoding='utf-8-sig') as f:
            # data_row[0] = self.readCsv()
            data_row[0] = self.assert_sm()[0]
            # print(type(data_row[0]))
            print(type(data_row[0]))
            f.write(','.join(data_row))
            f.write("\n")
            f.close()



if __name__ == '__main__':
    # 开始时间
    start = time.time()
    fd = smallTalkTest()
    fd.readCsv()
    fd.chatChit()
    fd.assert_sm()
    fd.saveCsv()
    # smf.close()
    # 计算花费的时间
    print('cost time:{}'.format(time.time() - start))

    print("------qa闲聊模型结果统计" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "------")
    print("qa问答失败"+str(fd.assert_sm()[1]))




